package com.sign.utils.sm2;

import org.bouncycastle.asn1.ASN1OctetString;
import org.bouncycastle.asn1.ASN1OctetStringParser;
import org.bouncycastle.asn1.ASN1Primitive;
import org.bouncycastle.asn1.ASN1Sequence;
import org.bouncycastle.asn1.pkcs.PrivateKeyInfo;
import org.bouncycastle.jce.provider.BouncyCastleProvider;
import org.bouncycastle.openssl.PEMKeyPair;
import org.bouncycastle.openssl.PEMParser;
import org.bouncycastle.openssl.jcajce.JcaPEMKeyConverter;

import java.io.StringReader;
import java.security.KeyPair;
import java.security.KeyPairGenerator;
import java.security.PrivateKey;
import java.security.Security;
import java.security.spec.ECGenParameterSpec;

public class SM2PrivateKeyUnwrap {
    public static void main(String[] args) throws Exception {
        // 添加Bouncy Castle作为安全提供者
        Security.addProvider(new BouncyCastleProvider());

        // 生成SM2密钥对
        KeyPairGenerator keyPairGenerator = KeyPairGenerator.getInstance("EC", "BC");
        ECGenParameterSpec ecGenParameterSpec = new ECGenParameterSpec("sm2p256v1");
        keyPairGenerator.initialize(ecGenParameterSpec);
        KeyPair keyPair = keyPairGenerator.generateKeyPair();


        String encryptedPrivateKey = "-----BEGIN EC PRIVATE KEY-----\n" +
                "MIIBTTAJBgcqgRzPVQFoMHgCID29P3ojQ7XKtULKqGpPEtduaF4vW743VHcMYhKEGOE/AiBIzqzrbh+NMobxAB4hgPorGSrhreSP3ZHaN/OUYU0cAQQgeu1RTRye2wauxmAipwjUt4sPhE+c6ZRmD0Z5p1QIaa0EEE5FzFT+IyEpy1JK1fKOissDQgAEqYLtADQdrY0BuPsPisGCGOG6WBkcdZ9RSuah+S+7sRzbAgrl4Q8VhMjXNgMvkUcBlLBSlI5PjjIimsKSkTzk0QOBgQCgkYwmB2UJlPZkBehKJemlDopOj6lnmJGDGmS7sGr74+GMbTzzNY8aVdUCtwYFdQZN04TSPUWUiEIxp6Sqe+pAGjc7WyZ99FPA+rDGuGX+AdM4Zr4ZfGmWSTxYRI5OmlM7cp80YyObDmF05FxMMGqVI9q6A9kyqfHyDCtez1owbg==\n" +
                "-----END EC PRIVATE KEY-----";
        String originPrivateKey = "MIGTAgEAMBMGByqGSM49AgEGCCqBHM9VAYItBHkwdwIBAQQgfNexq1nwpwktZQ4HdDmWm+qAuFtl\n" +
                "cBE4IYkMPrOUaImgCgYIKoEcz1UBgi2hRANCAAShR5qgWynwjP93rfFUVlJH0OsBENwbzBs/r8q1\n" +
                "5qoW38Qtpmy5ovyy8u+I6+mtge72jlovyuXuJe9igASGcmxM";
        PEMParser keyParser = new PEMParser(new StringReader(encryptedPrivateKey));
        JcaPEMKeyConverter converter = new JcaPEMKeyConverter();
        converter.setProvider("BC");
        PEMKeyPair pemKeyPair = (PEMKeyPair)keyParser.readObject();

        PrivateKeyInfo keyInfo = pemKeyPair.getPrivateKeyInfo();

        // 获取SM2私钥

        // 拆封SM2私钥保护结构
        byte[] wrappedPrivateKey = keyInfo.getEncoded();
        ASN1Primitive privateKeyInfo = ASN1Primitive.fromByteArray(wrappedPrivateKey);
        ASN1Sequence sequence = (ASN1Sequence) privateKeyInfo;
        ASN1OctetString privateKeyOctetString = (ASN1OctetString) sequence.getObjectAt(2);
        byte[] privateKeyBytes = privateKeyOctetString.getOctets();
        ASN1OctetStringParser parser = privateKeyOctetString.parser();
        ASN1Primitive asn1Primitive = parser.toASN1Primitive();
        // 输出拆封后的SM2私钥
        System.out.println("Unwrapped SM2 Private Key: " + bytesToHex(privateKeyBytes));
    }

    private static String bytesToHex(byte[] bytes) {
        StringBuilder sb = new StringBuilder();
        for (byte b : bytes) {
            sb.append(String.format("%02x", b));
        }
        return sb.toString();
    }
}
